package cn.yj.email;

import cn.yj.email.handle.EmailHandler;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <br>
 *
 * @author 永健
 * @since 2018/12/16 21:28
 */
@Component
class SpringBeanFactory implements ApplicationContextAware
{


    static ApplicationContext applicationContext;

    private static Map<String, EmailHandler> emailService = new HashMap<>();

    @Resource
    private Map<String, EmailHandler> emailServiceMap;


    @Override
    public void setApplicationContext(ApplicationContext act) throws BeansException
    {
        //获得所有serviceBeans
        applicationContext = act;
        emailService = emailServiceMap;
    }


    public static ApplicationContext getApplicationContext()
    {
        return applicationContext;
    }

    public static <T> T getBeans(String beanStr)
    {
        T bean = null;
        try {
            bean = (T) getApplicationContext().getBean(beanStr);
        } catch (BeansException e) {
            System.out.println("获取Bean失败/找不到bean: " + beanStr);
            return null;
        }
        return bean;
    }

    public static EmailHandler emaiInstance(String beanStr)
    {
        EmailHandler emailHandler = emailService.get(beanStr);
        return emailHandler;
    }


    public static <T> T getBeans(Class<T> tCalss)
    {
        T bean = null;
        try {
            bean = (T) getApplicationContext().getBean(tCalss);
        } catch (BeansException e) {
            System.out.println("获取Bean失败/找不到bean: " + tCalss.getSimpleName());
            return null;
        }
        return bean;
    }

}
